package org.csu.mypetstore.service.impl;

import net.sf.json.JSONObject;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.persistence.CartMapper;
import org.csu.mypetstore.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;


    @Override
    public List<String> getItemsinCart(Account account) {
        return cartMapper.getItems(account);
    }

    @Override
    public void insertItemToCart(Account account, String itemId) {
        if(cartMapper.isExit(account,itemId) == null) {
            cartMapper.insertCart(account, itemId);
        }else{
            cartMapper.addIteminCart(account,itemId);
        }
    }

    @Override
    public void deleteItemFromCart(Account account, String itemId) {
        cartMapper.deleteCart(account,itemId);
    }

    @Override
    public void minusCart(Account account, String itemId) {
        cartMapper.minusCart(account,itemId);
        String temp = cartMapper.isExit(account,itemId);
        //System.out.println(temp);
        if(temp.equals("0")){
            cartMapper.deleteCart(account,itemId);
        }
    }

    @Override
    public void clearUpCart(Account account) {
        cartMapper.clearUpCart(account);
    }

    @Override
    public int getNum(Account account, String itemId) {
        return Integer.valueOf(cartMapper.getNum(account,itemId));
    }

    @Override
    public JSONObject getItemInfo(Account account, String itemId) {
        String num = cartMapper.getNum(account,itemId);
        String price = cartMapper.getPrice(itemId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("num",num);
        jsonObject.put("price",price);
        return jsonObject;
    }

}
